package com.maxmlr.concurrent.cyclic;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName Producer
 * @Description TODO
 * @Author maxiao
 * @Date 2020/3/5 上午11:22
 * @Version V1.0
 */
public class Producer implements Runnable {

    public Message msg;

    private CyclicBarrier cyclicBarrier;

    CountDownLatch countDownLatch = new CountDownLatch(1);

    Random random = new Random();

    public Producer(String key) {
        msg = new Message();
        msg.key = key;
    }

    public String getKey() {
        return msg.key;
    }

    public void setCode(String code) {
        msg.code = code;
    }

    public Producer(String key, CyclicBarrier cyclicBarrier) {
        msg = new Message();
        msg.key = key;
        this.cyclicBarrier = cyclicBarrier;
    }

    public boolean flag(){
        return msg.flag();
    }

    @Override
    public void run() {
        TestCyclic.map.put(getKey(), this);
        System.out.println(Thread.currentThread().getName()+"---"+getKey() + ":发送事件");
        try {
            //这里采用闭锁的线程切换功能。
            countDownLatch.await(1500, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }


        System.out.println("换起线程："+Thread.currentThread().getName());
        System.out.println("msg:"+msg);

        // 等待所有任务准备就绪
        try {
            cyclicBarrier.await(2000,TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}
